<template>
  <div class="main">
  <canvas id="c"></canvas>
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <a-tabs
        :activeKey="customActiveKey"
        :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick"
      >
        <a-tab-pane key="tab1" tab="账号密码登录">
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="账户: admin"
              v-decorator="[
                'username',
                {rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
              ]"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-input
              size="large"
              type="password"
              autocomplete="false"
              placeholder="密码: admin"
              v-decorator="[
                'password',
                {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
              ]"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>

      <a-form-item>
        <a-checkbox v-decorator="['rememberMe']">自动登录</a-checkbox>
      </a-form-item>

      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >确定</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import md5 from 'md5'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions ,mapGetters} from 'vuex'
import { timeFix } from '@/utils/util'
import { getSmsCaptcha, get2step } from '@/api/login'

export default {
  components: {
    
  },
  data() {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created() {
    
    // this.requiredTwoStepCaptcha = true
  },
  mounted() {
    let dimensions = [document.documentElement.clientWidth, document.documentElement.clientHeight]

    let mouseX
    let mouseY

    let radius
    const d2r = 0.0174533

    let cx
    let cy

    let prism

    let canvas
    let ctx

    let el = []

    let poly
    let poly2

    const init = () => {
      dimensions = [document.documentElement.clientWidth, document.documentElement.clientHeight]

      mouseX = dimensions[0] / 2
      mouseY = dimensions[1] / 2

      radius = 50
      // const d2r = 0.0174533;

      cx = Math.sin(60 * 0.0174533) * radius
      cy = radius * 1.5

      prism = Math.ceil(dimensions[0] / cx)

      canvas = document.getElementById('c')
      canvas.width = dimensions[0]
      canvas.height = dimensions[1]
      ctx = canvas.getContext('2d')

      el = []
      for (let x = 0; x < prism * prism; x++) {
        el.push([Math.random(), 0.5])
      }

      poly = [
        Math.sin(0 * d2r) * radius,
        Math.cos(0 * d2r) * radius,
        Math.sin(120 * d2r) * radius,
        Math.cos(120 * d2r) * radius,
        Math.sin(240 * d2r) * radius,
        Math.cos(240 * d2r) * radius
      ]

      poly2 = [
        Math.sin(180 * d2r) * radius,
        Math.cos(180 * d2r) * radius,
        Math.sin(300 * d2r) * radius,
        Math.cos(300 * d2r) * radius,
        Math.sin(60 * d2r) * radius,
        Math.cos(60 * d2r) * radius
      ]
    }

    const render = t => {
      const timer = Math.sin(t * 0.01)
      ctx.clearRect(0, 0, dimensions[0], dimensions[1])
      for (let x = 0; x < prism * prism; x++) {
        const dist = Math.hypot(mouseX - ((x % prism) * cx + cx / 2), mouseY - (Math.floor(x / prism) * cy + cy / 2))
        let alpha = 1 - Math.abs(dimensions[0] / 2 / dist) / 2

        el[x][0] += 0.01 * el[x][1]
        alpha += el[x][0]

        if (el[x][0] > 1) {
          el[x][1] = -1
        } else if (el[x][0] < 0) {
          el[x][1] = 1
        }

        const _x = (x % prism) * cx
        const _y = Math.floor(x / prism) * cy

        ctx.fillStyle = `hsla(0,100%,100%,${alpha})`
        ctx.beginPath()
        if (x % 2 == 0) {
          let o = radius / 2
          ctx.moveTo(_x + poly[0], _y + poly[1] - o)
          ctx.lineTo(_x + poly[2], _y + poly[3] - o)
          ctx.lineTo(_x + poly[4], _y + poly[5] - o)
        } else {
          ctx.moveTo(_x + poly2[0], _y + poly2[1])
          ctx.lineTo(_x + poly2[2], _y + poly2[3])
          ctx.lineTo(_x + poly2[4], _y + poly2[5])
        }
        ctx.closePath()
        ctx.fill()
      }

      requestAnimationFrame(render)
    }

    init()
    render()

    window.addEventListener('mousemove', e => {
      mouseX = e.clientX
      mouseY = e.clientY
    })

    window.addEventListener('touchmove', e => {
      mouseX = e.touches[0].pageX
      mouseY = e.touches[0].pageY
    })

    window.addEventListener('resize', e => {
      init()
    })
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    ...mapGetters(['nickname']),
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          loginParams[!state.loginType ? 'email' : 'username'] = values.username
          loginParams.password = values.password
          Login(loginParams)
            .then(res => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                duration: 8
              })
            })
            .catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess(res) {
      this.$router.push({ name: 'dashboard' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: res.data.name,
          description: `${timeFix()}，欢迎回来`,
          duration:3
        })
      }, 1000)
    },
    requestFailed(err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || err || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
canvas {
  width: 100vw;
  height: 100vh;
  mix-blend-mode: overlay;
  position: absolute;
  top:0;
  left: 0;
}
</style>
